package com.b2c.erp.controller.zbj;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.api.ApiResult;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.erp.ErpSalesOrderItemEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.enums.erp.EnumErpOrderStatus;
import com.b2c.entity.enums.erp.EnumSalesOrderPayStatus;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ErpContactEntity;
import com.b2c.repository.utils.OrderNumberUtils;
import com.b2c.interfaces.wms.ClientManageService;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.erp.ErpSalesOrderService;
import com.b2c.entity.vo.erp.ErpSalesOrderDetailVo;
import com.b2c.entity.SampleListEntity;
import com.b2c.interfaces.SampleService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/zbj")
@Controller
public class ZbjSampleController {
    @Autowired
    private ClientManageService clientManageService;
    @Autowired
    private SampleService sampleService;
    @Autowired
    private ErpGoodsService erpGoodsService;
    @Autowired
    private ErpSalesOrderService erpSalesOrderService;

    private static Logger log = LoggerFactory.getLogger(ZbjSampleController.class);
    /**
     * 直播间样品管理
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/sample_list", method = RequestMethod.GET)
    public String sampleList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }

        PagingResponse<ErpContactEntity> zbj = clientManageService.getClientList(1, 10, "", "",-10,99);

        model.addAttribute("zbj", zbj.getList());
        Integer zbjId = null;
        if(!StringUtils.isEmpty(request.getParameter("zbjId"))) {
            zbjId = Integer.parseInt(request.getParameter("zbjId"));
            model.addAttribute("zbjId",zbjId);
        }
        String goodsNum=null;
        if(!StringUtils.isEmpty(request.getParameter("goodsNum"))) {
            goodsNum = request.getParameter("goodsNum");
            model.addAttribute("goodsNum",goodsNum);
        }
        String orderDate=null;
        if(!StringUtils.isEmpty(request.getParameter("orderDate"))) {
            orderDate = request.getParameter("orderDate");
            model.addAttribute("orderDate",orderDate);
        }

        var sampleList = sampleService.getSampleList(pageIndex,20,goodsNum,orderDate,zbjId);
        model.addAttribute("totalSize", sampleList.getTotalSize());
        model.addAttribute("lists", sampleList.getList());

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);


        model.addAttribute("view", "livedata");
        model.addAttribute("pView", "sale");
        Integer isPrint = 0;
        if(!StringUtils.isEmpty(request.getParameter("isPrint"))) {
            isPrint = Integer.parseInt(request.getParameter("isPrint"));
        }
        if(isPrint == 1){
            return "zbj/sample_list_print";
        }else return "zbj/sample_list";
    }

    /**
     * 直播间下样品单
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/excel_sample_import", method = RequestMethod.GET)
    public String excel_sample_import(Model model, HttpServletRequest request){
        PagingResponse<ErpContactEntity> clientList = clientManageService.getClientList(1, 100, null, null,-10,99);//-10代表是客户
        model.addAttribute("clientList", clientList.getList());
        model.addAttribute("view", "zbjypgl");
        model.addAttribute("pView", "fx");
        return "zbj/sample_excel_import";
    }

    /**
     * 直播间下样品单POST
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/excel_sample_import", method = RequestMethod.POST)
    public String excel_sample_import_post(Model model, HttpServletRequest request) {
        Integer buyerUserId = Integer.parseInt(request.getParameter("buyerUserId"));
        String sellerMemo = request.getParameter("sellerMemo");
        //specNumber,quantity
        String[] specNumber = request.getParameterValues("specNumber");//规格编码组合
        String[] quantitys = request.getParameterValues("quantity");//数量组合

        //查询直播间
        var zbj = clientManageService.getClientById(buyerUserId);

        ErpSalesOrderDetailVo salesOrder = new ErpSalesOrderDetailVo();
        List<ErpSalesOrderItemEntity> items = new ArrayList<>();
        Long goodsCount = 0L;//商品数量
        Long goodsSpecCount = 0L;//商品规格数量
        double goodsTotalAmount = 0;//商品总价

        for (int i = 0, n = specNumber.length; i < n; i++) {
            if (StringUtils.isEmpty(specNumber[i])) continue;

            ErpSalesOrderItemEntity item = new ErpSalesOrderItemEntity();
            //查询商品
            var spec = erpGoodsService.getSpecByNumber(specNumber[i]);
            if(spec == null ){
                String msg = "Not Found，SKU:"+specNumber[i];
                log.info(msg);
                return "redirect:/sys_err?msg="+msg;
            }

            String specNum = specNumber[i];
            Integer count = Integer.parseInt(quantitys[i]);

            //if(count.intValue()>spec.getCurrentQty())continue;
            goodsCount += count;
            goodsSpecCount++;
            goodsTotalAmount += spec.getSalePrice() * count;

            item.setGoodsId(spec.getGoodsId());
            item.setSpecId(spec.getId());
            item.setSpecNumber(specNumber[i]);
            item.setGoodsNumber(spec.getGoodsNumber());
            item.setQuantity(count);
            item.setPrice(new BigDecimal(spec.getSalePrice()));
            item.setDiscountPrice(new BigDecimal(spec.getSalePrice()));
            item.setGoodsTitle(spec.getGoodTitle());
            item.setGoodsImage(spec.getColorImage());
            item.setColor(spec.getColorValue());
            item.setSize(spec.getSizeValue());
            item.setSkuInfo(item.getColor() + " " + item.getSize());
            items.add(item);
        }

        salesOrder.setGoodsCount(goodsCount);
        salesOrder.setGoodsSpecCount(goodsSpecCount);
        salesOrder.setGoodsTotalAmount(new BigDecimal(goodsTotalAmount));
        salesOrder.setContactMobile("13000000000");
        salesOrder.setContactPerson(zbj.getName());
        salesOrder.setProvince("广东省");
        salesOrder.setCity("东莞市");
        salesOrder.setArea("大朗镇");
        salesOrder.setAddress("直播间");
        salesOrder.setItems(items);
        salesOrder.setSaleType(0);
        salesOrder.setShippingFee(new BigDecimal(0));
        salesOrder.setBuyerUserId(buyerUserId);
        salesOrder.setBuyerName(zbj.getName());
        salesOrder.setShopId(99);
        salesOrder.setOrderNum(OrderNumberUtils.getOrderIdByTime());
        salesOrder.setTotalAmount(new BigDecimal(goodsTotalAmount).add(new BigDecimal(0)));
        salesOrder.setOrderTime(System.currentTimeMillis() / 1000);
        //未付款订单
        salesOrder.setStatus(EnumErpOrderStatus.WaitSend.getIndex());
        salesOrder.setPayAmount(new BigDecimal(0));//付款金额
        salesOrder.setPayTime(0L);
        salesOrder.setPayStatus(EnumSalesOrderPayStatus.NotPay.getIndex());
        salesOrder.setPayMethod(0);
        salesOrder.setOrderDate(DateUtil.getCurrentDate());
        salesOrder.setShippingFee(new BigDecimal(0));
        salesOrder.setSellerMemo(sellerMemo);
        salesOrder.setCreateOn(System.currentTimeMillis() / 1000);
        salesOrder.setAuditStatus(0);

        if (goodsCount > 0) {
          var result =   erpSalesOrderService.editSalesOrder(salesOrder);
          if(result.getCode() == 0) {
              log.info("excel导入样品下单成功");
          }else
              log.info("excel导入样品下单失败。"+result.getMsg());
        }
        return "redirect:/zbj/sample_list";
    }

    /**
     * 下样品单导入商品
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @ResponseBody
    @RequestMapping(value = "/excel_sample_import_ajax", method = RequestMethod.POST)
    public ApiResult<List<ZbjSampleExecelImportVo>> zhubo_order_import_excel_settle(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
//        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********导入下单商品，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");

        XSSFSheet sheet;
        InputStream fis = null;

        fis = new FileInputStream(destFileName);

        //订单list
        HashMap<String,Integer> goodsList = new HashMap<>();
        List<ZbjSampleExecelImportVo> list = new ArrayList<>();
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(fis);
            log.info("/***********导入下单商品***读取excel文件成功***********/");

            sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();//最后一行索引
            XSSFRow row = null;

            //订单实体
            for (int i = 1; i <= lastRowNum; i++) {
                row = sheet.getRow(i);
                String skuCode = row.getCell(0).getStringCellValue();
                Double count = row.getCell(1).getNumericCellValue();
                goodsList.put(skuCode,count.intValue());
            }
            log.info("/***********导入下单商品***读取excel文件结果"+ JSONObject.toJSONString(goodsList) +"***********/");


            for (Map.Entry<String, Integer> entry : goodsList.entrySet()) {
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
//                var g = erpGoodsService.getGoodsSpecDetailByNumber(entry.getKey());
                ZbjSampleExecelImportVo vo = new ZbjSampleExecelImportVo();
                vo.setCode(entry.getKey());
                vo.setCount(entry.getValue());
                list.add(vo);
            }

//            douyinOrderService.zhuBoOrderSettle(orderList,1);
        }catch (Exception e){
            log.info("/***********导入下单商品***出现异常：" + e.getMessage() + "***********/");
            return new ApiResult<>(500, e.getMessage());
        }
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(),"成功",list);
    }


    /**
     * 导出数据
     * @param req
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/sample_list_export")
    public void erpStockOutItemRefundInvoiceExport(HttpServletRequest req, HttpServletResponse response) throws Exception {
        //直播间ID
        Integer zbjId = null;
        if(!StringUtils.isEmpty(req.getParameter("zbjId"))) {
            zbjId = Integer.parseInt(req.getParameter("zbjId"));
        }

        String orderDate=StringUtils.isEmpty(req.getParameter("orderDate")) ? null : req.getParameter("orderDate");


        var result = sampleService.getSampleList(0,null,"",orderDate,zbjId);
        var lists = result.getList();

        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "sample_list_export_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);

        cell = row.createCell(0);
        cell.setCellValue("序号");
        cell = row.createCell(1);
        cell.setCellValue("拿样日期");
        cell = row.createCell(2);
        cell.setCellValue("SKU编码");
        cell = row.createCell(3);
        cell.setCellValue("规格信息");
        cell = row.createCell(4);
        cell.setCellValue("数量");
        cell = row.createCell(5);
        cell.setCellValue("直播间");
        cell = row.createCell(6);
        cell.setCellValue("样品状态");


        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            SampleListEntity itemVo = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(i+1);
            //商品名称
            cell = row.createCell(1);
            cell.setCellValue(itemVo.getOrderDate());
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getSpecNumber());

            cell = row.createCell(3);
            cell.setCellValue(itemVo.getSkuInfo());

            cell = row.createCell(4);
            cell.setCellValue(itemVo.getQuantity());
            cell = row.createCell(5);
            cell.setCellValue(itemVo.getBuyerName());
            //zt
            String status = "";
            if(itemVo.getItemStatus().intValue() == 0){
                status="仓库未发货";
            }else if(itemVo.getItemStatus().intValue() == 1){
                status= "仓库已发货";
            }if(itemVo.getItemStatus().intValue() == 2){
                status = "样品已退回";
            }
            cell = row.createCell(6);
            cell.setCellValue(status);

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }
}
